﻿using System;
using System.Web.Mvc;
using System.Collections.Generic;

using Microsoft.Practices.Unity;

namespace Kratos.Framework.Infrastructures
{
    public class KratosDependencyResolver : IDependencyResolver
    {
        private readonly IUnityContainer _container;

        public KratosDependencyResolver(IUnityContainer container)
        {
            _container = container;
        }

        public object GetService(Type serviceType)
        {
            return TryGetSerivce(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return TryGetServices(serviceType);
        }

        private object TryGetSerivce(Type serviceType)
        {
            if (serviceType == null)
                return null;

            try
            {
                return _container.Resolve(serviceType);
            }
            catch
            {
                return null;
            }
        }

        private IEnumerable<object> TryGetServices(Type serviceType)
        {
            if (serviceType == null)
                return null;

            try
            {
                return _container.ResolveAll(serviceType);
            }
            catch
            {
                return null;
            }
        }
    }
}
